package com.want.evenchat.controller.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.Window;
import android.widget.Toast;
import com.hyphenate.chat.EMClient;
import com.want.evenchat.R;
import com.want.evenchat.model.Model;
import com.want.evenchat.model.bean.UserInfo;

/**
 * Created by Want on 2018/5/3.
 */

public class SplashActivity extends Activity {

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            //如果当前Activity已经推出，那么就不处理handler的消息
            if (isFinishing()){
                return;
            }

            //判断进入主页面还是登录页面
            toMainOrLogin();
        }


    };
    private void toMainOrLogin() {
//        new Thread(){
//            @Override
//            public void run() {
//
//            }
//        }.start();

        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                //判断当前账号是否已经登录过
                if (EMClient.getInstance().isLoggedInBefore()){//已经登录

                    //获取到当前登录的用户信息
                    UserInfo account = Model.getInstance().getUserAccountDao().getAccountByHxid(EMClient.getInstance().getCurrentUser());
                    if (account == null){
                        //跳转到登录页面
                        startActivity(new Intent(SplashActivity.this , LoginActivity.class));
                    }else {

                        //登录成功后的方法
                        Model.getInstance().loginSuccess(account);

                        startActivity(new Intent(SplashActivity.this , MainActivity.class));
                    }

                    //跳转到主页面
                    startActivity(new Intent(SplashActivity.this,MainActivity.class));
                    finish();
                }else {//没有登录
                    //跳转到登录页面
                    startActivity(new Intent(SplashActivity.this,LoginActivity.class));

                }
                //结束当前页面
                finish();
            }
        });
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_splash);

        //发送2s秒的延时消息
        handler.sendMessageDelayed(Message.obtain(),2500);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁消息
        handler.removeCallbacksAndMessages(null);
    }
}
